//
//  CardItemView.m
//  3dtest
//
//  Created by XL on 2022/7/21.
//

#import "CardItemView.h"
#import "Masonry.h"

@interface CardItemView()

@property (nonatomic , nonnull , strong) NSString * filePath;

/// 是否在滑动的动画中
@property (nonatomic , assign) BOOL isAnimationing;

@end

@implementation CardItemView

+ (CGFloat)cardWidth {
    return [[[UIApplication sharedApplication] windows] objectAtIndex:0].frame.size.width - 40.0;
}

+ (CGFloat)cardHeight {
    return [CardItemView cardWidth] * 1;
}

/// 构建方法：通过文件路径
/// @param path 可以是沙盒里的，也可以是bundle里的
/// bundle：let filePath = Bundle.main.path(forResource: name, ofType: nil)
/// 沙盒：直接把文件路径丢进来
- (instancetype)initWithFilePath:(NSString *)path{
    if (self = [super initWithFrame:CGRectZero]) {
        self.filePath = [path copy];
        [self buildUI];
    }
    return self;
}

- (void)buildUI {

    GLTFSceneSource *source = [[GLTFSceneSource alloc] initWithURL:[NSURL fileURLWithPath:self.filePath] options:nil];
    NSError *error;
    SCNScene *scene = [source sceneWithOptions:nil error:&error];
    if (error != nil) {
      NSLog(@"%@", error);
      return;
    }
    
    self.scnView = [SCNView new];
    self.scnView.scene = scene;
    self.scnView.autoenablesDefaultLighting = YES;
    self.scnView.scene.rootNode.scale = (SCNVector3){1,1,1};
    self.scnView.antialiasingMode = SCNAntialiasingModeMultisampling4X;
    self.scnView.scene.lightingEnvironment.contents = [UIImage imageNamed:@"studio021-4.png"];
    [self addSubview:self.scnView];
    [self.scnView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cardTap)];
    self.scnView.userInteractionEnabled = YES;
    [self.scnView addGestureRecognizer:tap];
    

    
}

- (void)cardTap {
    if (self.clickBlock != nil) {
        self.clickBlock();
    }
}

/// 翻转卡片
- (void)flipViewByRate:(CGFloat)rate {
    if (self.isAnimationing == YES) {
        return;
    }
    self.currentRotationY += (rate > 0 ? M_PI : -M_PI);
    [self.scnView.scene.rootNode runAction:[SCNAction rotateToX:0 y:self.currentRotationY z:0 duration:0.35] completionHandler:^{
        if (fabs(self.currentRotationY / 2) == M_PI) {
            self.currentRotationY = 0;
            self.scnView.scene.rootNode.rotation = (SCNVector4){0,0,0,0};
        }
    }];
}

/// 用与滑动时的翻转
/// @param ratio 翻转比例
- (void)animationToRatio:(CGFloat)ratio {
    self.isAnimationing = YES;
    CGFloat y = self.currentRotationY;
    CGFloat dealValue = M_PI * ratio;
    y = y + dealValue;
    [self.scnView.scene.rootNode runAction:[SCNAction group:@[[SCNAction scaleTo:0.9  duration:0.25],[SCNAction rotateToX:0 y:y z:0 duration:0.25]]] completionHandler:^{
        self.isAnimationing = NO;
    }];
}

/// 用与滑动结束时的翻转
/// @param ratio 翻转方向
/// @param status 是否完成
- (void)animationToRatio:(CGFloat)ratio status:(BOOL)status isCurrent:(BOOL)isCurrent{
    self.isAnimationing = YES;
    CGFloat dealValue = status ? (ratio > 0 ? M_PI : -M_PI) : 0;
    self.currentRotationY += dealValue;

    [self.scnView.scene.rootNode runAction:[SCNAction group:@[[SCNAction scaleTo:1 duration:0.25],[SCNAction rotateToX:0 y:self.currentRotationY z:0 duration:0.25]]] completionHandler:^{
        self.isAnimationing = NO;
        if (isCurrent == NO && status == YES) {//把不是当前页的其他卡片设置为反面，一定要下一帧，不然会失效
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.currentRotationY = -M_PI;
                [self.scnView.scene.rootNode runAction:[SCNAction rotateToX:0 y:self.currentRotationY z:0 duration:0] completionHandler:^{
                }];
            });
        }
    }];
}



@end
